package com.ikingtech.platform.service.authentication.web;

import com.ikingtech.platform.service.authentication.converter.AuthenticateConverterManager;
import com.ikingtech.platform.service.authentication.endpoint.AuthenticateEndpoint;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class AuthenticationFilter extends OncePerRequestFilter {

    private final AuthenticateConverterManager converterManager;

    private final List<AuthenticateEndpoint> endpoints;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        AuthenticationRequest authenticationRequest = this.converterManager.convert(request);
        if (null == authenticationRequest) {
            filterChain.doFilter(request, response);
            return;
        }

        for (AuthenticateEndpoint endpoint : this.endpoints) {
            if (endpoint.support(authenticationRequest.getEndpointUri())) {
                endpoint.authenticate(authenticationRequest);
                return;
            }
        }
    }
}
